package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.CountyIndicatorsMapper;
import com.cmii.sjw.department.control.jsc.model.CountyIndicators;
import com.cmii.sjw.department.control.jsc.model.UniversityIndicators;
import com.cmii.sjw.department.control.jsc.model.vo.UniversityIndicatorVo;
import com.cmii.sjw.department.control.jsc.service.CountyIndicatorsService;
import com.cmii.sjw.department.control.jsc.vo.CityVO;
import com.cmii.sjw.department.control.jsc.vo.CountyIndicatorsVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service("CountyIndicatorsService")
public class CountyIndicatorsServiceImpl extends ServiceImpl<CountyIndicatorsMapper, CountyIndicators> implements CountyIndicatorsService {
    @Autowired
    private CountyIndicatorsMapper countyIndicatorsMapper;

    @Override
    public Map<String, Map<String,String>> listByCountyIndicators(String secondLevelIndicatorName) {
        List<CountyIndicators> list = countyIndicatorsMapper.selectList(
                new LambdaQueryWrapper<CountyIndicators>()
                        .like(StringUtils.isNotBlank(secondLevelIndicatorName), CountyIndicators::getSecondLevelIndicatorName, secondLevelIndicatorName)
                        .eq(CountyIndicators::getIsDeleted, 0)
                        .orderByAsc(CountyIndicators::getSubModule)
        );

        Map<String, Map<String, String>> result = new LinkedHashMap<>();

        result.put("xueqian", new LinkedHashMap<>() {{
            put("gongbanyoueryuan", "0");
            put("puhuiyoueryuan", "0");
            put("minbanyoueryuan","0");
        }});
        result.put("yiwu", new LinkedHashMap<>() {{
            put("yiwujiaoyuzonghe", "0");
            put("xiaoxuejiaoyuziyuan", "0");
            put("chuzhongjiaoyuziyuan", "0");
            put("duxue", "0");
            put("minbanzaixiaoshengguimo", "0");
            put("minbannianjiantongguolv", "0");
            put("bane", "0");
            put("xiaoe", "0");
        }});
        result.put("teshu", new LinkedHashMap<>() {{
            put("canjirenxuelv", "0");
        }});
        result.put("gaozhong", new LinkedHashMap<>() {{
            put("minbangaozhong", "0");
            put("banxuetiaojian", "0");
            put("zonghegaozhongzaixiaoshengguimo", "0");
            put("zonghegaozhongzhongzhixuexiaoshu", "0");
            put("shuangwujihua", "0");
            put("guantongpeiyang", "0");
            put("zaixiaoshengguimo", "0");
            //put("sjsfxjxjyjd", BigDecimal.ZERO);
            put("sjcjrhsxjd", "0");
            put("sjcjrhsdcs", "0");
            put("zyjyggcxmxqx", "0");
            put("hdgjj", "0");
            put("jsgjjghjcs","0");
            put("sjqszyyxjndshjs", "0");
            put("qgqszyyxjndsjxnlbshjs", "0");
            put("zyyxjnds", "0");
        }});
        result.put("zhongshen", new LinkedHashMap<>() {{
            put("sqjysjbxjgs", "0");
            put("sjlndxsfx", "0");
            put("sjsqjy","0");
            put("xsdbxxxzx", "0");
        }});
        for (CountyIndicators item : list) {
            String subModuleKey = toShortKey(item.getSubModule());
            String indicatorKey = toEnglishIndicatorKey(item.getFirstLevelIndicatorName());

            if (result.containsKey(subModuleKey) && result.get(subModuleKey).containsKey(indicatorKey)) {
                result.get(subModuleKey).put(indicatorKey, item.getSecondLevelIndicatorValue());
            }
        }

        return result;
    }

    private String toEnglishIndicatorKey(String name){
        switch (name){
            // 学前教育
            case "公办园在园幼儿占比":
                return "gongbanyoueryuan";
            case "普惠性幼儿园覆盖率":
                return "puhuiyoueryuan";
            case "民办幼儿园年检通过率":
                return "minbanyoueryuan";

            // 义务教育
            case "义务教育综合质量系数":
                return "yiwujiaoyuzonghe";
            case "小学教育资源配置差异系数":
                return "xiaoxuejiaoyuziyuan";
            case "初中教育资源配置差异系数":
                return "chuzhongjiaoyuziyuan";
            case "督学入校督导次数":
                return "duxue";
            case "民办义务教育在校生规模占比":
                return "minbanzaixiaoshengguimo";
            case "民办义务教育年检通过率":
                return "minbannianjiantongguolv";
            case "小学标准班额":
                return "bane";
            case "小学标准校额":
                return "xiaoe";

            // 特殊教育
            case "适龄残疾儿童少年入学率":
                return "canjirenxuelv";

            // 高中阶段协调平衡
            case "民办高中年检通过率":
                return "minbangaozhong";
            case "办学条件重点监测指标全部达标学校比例":
                return "banxuetiaojian";
            case "综合高中试点在校生规模":
                return "zonghegaozhongzaixiaoshengguimo";
            case "综合高中试点中职学校数":
                return "zonghegaozhongzhongzhixuexiaoshu";
            case "“双优计划”中职学校数":
                return "shuangwujihua";
            case "贯通培养试点中职学校数":
                return "guantongpeiyang";
            case "贯通培养试点在校生规模":
                return "zaixiaoshengguimo";
//            case "市级示范性继续教育基地、社区教育示范基地数":
//                return "sjsfxjxjyjd";
            case "市级产教融合实训基地、虚拟仿真实训基地":
                return "sjcjrhsxjd";
            case "市级产教融合试点城市":
                return "sjcjrhsdcs";
            case "职业教育改革成效明显区县":
                return "zyjyggcxmxqx";
            case "获得国家级、市级教学成果奖数":
                return "hdgjj";
            case "建设国家级规划教材数":
                return "jsgjjghjcs";
            case "世界、全市职业院校技能大赛获奖数":
                return "sjqszyyxjndshjs";
            case "全国、全市职业院校技能大赛教学能力比赛获奖数":
                return "qgqszyyxjndsjxnlbshjs";
            case "全国、全市职业院校技能大赛德育与思想政治教育有关赛项获奖数":
                return "zyyxjnds";
            // 终身教育泛在可及
            case "社区教育四级办学机构数":
                return "sqjysjbxjgs";
            case "市级老年大学示范校、老年教育试点校数":
                return "sjlndxsfx";
            case "市级示范性继续教育基地、社区教育示范基地数":
                return "sjsqjy";
            case "新时代“百姓学习之星”和“终身学习品牌项目”数":
                return "xsdbxxxzx";
            default:
                return "other";
        }
    }
    private String toShortKey(String subModule) {
        switch (subModule) {
            case "义务教育优质均衡":
                return "yiwu";
            case "学前教育普及普惠":
                return "xueqian";
            case "特殊教育普惠发展":
                return "teshu";
            case "高中阶段协调平衡":
                return "gaozhong";
            case "终身教育泛在可及":
                return "zhongshen";
            default:
                return "other";
        }
    }

    @Override
    public List<Map<String, String>> listByCityIndicators() {
        List<CityVO> list = countyIndicatorsMapper.selectGroupedByCounty();

        Map<String, Map<String, String>> tempMap = new LinkedHashMap<>();

        Map<String, String> indicatorKeyMap = new HashMap<>();
        indicatorKeyMap.put("义务教育综合质量系数", "yiwu");
        indicatorKeyMap.put("基础教育共同体覆盖率", "jichu");
        indicatorKeyMap.put("适龄残疾儿童少年入学率", "shiling");

        for (CityVO dto : list) {
            String county = dto.getSecondLevelIndicatorName();
            String name = dto.getFirstLevelIndicatorName();
            String value = dto.getSecondLevelIndicatorValue();

            String enKey = indicatorKeyMap.get(name);
            if (enKey == null) continue;

            tempMap.computeIfAbsent(county, k -> {
                Map<String, String> m = new LinkedHashMap<>();
                m.put("county", county);
                return m;
            }).put(enKey, value);
        }

        return new ArrayList<>(tempMap.values());
    }

    /**
     * 区县-学校治理KPI指标
     * @param countyName 区县名
     * @return 区县指标
     * @author jfh
     * @date 2025-08-28
     */
    @Override
    public Map<String, UniversityIndicatorVo> qxXxzlKpi(String countyName) {
        // KPI
        // 查询数据库
        List<CountyIndicators> indicatorsList = Optional.ofNullable(countyIndicatorsMapper.selectList(
                new LambdaQueryWrapper<CountyIndicators>()
                        .eq(CountyIndicators::getSubModule, "关键绩效指标")
                        .eq(CountyIndicators::getSecondLevelIndicatorName, countyName)
        )).orElse(Collections.emptyList());

        Map<String, UniversityIndicatorVo> retMap = new HashMap<>();

        // 使用Map来存储映射关系，提高可读性和性能
        Map<String, String> firstLevelMapping = new HashMap<String, String>() {{
            put("教育入学“一件事”覆盖率", "a");
            put("教育入学“一件事”家长满意率", "b");
            put("适龄残疾儿童少年入学率", "c");
            put("义务教育阶段大班额班占比", "d");
            put("青少年法治教育实践共享场馆", "e");
            put("涉教信访件（季）办结率", "f");
            put("中小学党组织领导的校长负责制落实率", "g");
            put("义务教育阶段（小学）优质均衡差异系数", "h");
            put("义务教育阶段（初中）优质均衡差异系数", "i");
            put("公办幼儿园在园幼儿占比", "j");
            put("成立家长委员会的学校比例", "k");
        }};

        // 初始化所有可能的key到retMap，默认值包含指标名称，值为"0"
        firstLevelMapping.forEach((indicatorName, key) -> {
            UniversityIndicatorVo vo = new UniversityIndicatorVo();
            vo.setIndicatorName(indicatorName);
            vo.setIndicatorValue("-");
            vo.setTargetValue("-");
            retMap.put(key, vo);
        });

        indicatorsList.forEach(item -> {
            String firstLevelName = item.getFirstLevelIndicatorName();
            // 优先处理第一级指标
            if (firstLevelMapping.containsKey(firstLevelName)) {
                UniversityIndicatorVo vo = new UniversityIndicatorVo();
                vo.setIndicatorName(firstLevelName);
                vo.setIndicatorValue(item.getSecondLevelIndicatorValue());
                vo.setTargetValue(item.getSecondLevelTargetValue());
                retMap.put(firstLevelMapping.get(firstLevelName), vo);
            }
        });

        return retMap;
    }
}
